package server;

import java.util.*; 
import java.sql.*; 
import java.io.*; 

/** 
* This file contains the code for the SerializedRS. 
* It acts as a wrapper class for the JDBC Result Set class.
* Creation date: 20/05/2014
* @author: Tomer Elkayam 
* 
*/ 

public class SerializedRS
{
	
	/** The row set. */
	private ArrayList<HashMap<String,String>> rowSet;	// Rowset for storing the ResultSet Data 
	
	/** The row count. */
	private int rowCount; 								// Number of rows retreived from the Database 
	
	/** The blankspace. */
	private String BLANKSPACE;	 						// Used to fill the null fields in database 

	/**
	 * SerializedRS constructor.
	 *
	 * @param rs the rs
	 * @throws SQLException the SQL exception
	 */ 
	public SerializedRS(ResultSet rs) throws SQLException 
	{
		rowSet = new ArrayList<HashMap<String,String>>();
		rowCount = 0; 
		BLANKSPACE = "";
		populateRecords(rs);
	}
	
	/**
	 *  
	 * This method is used to return the number of records in the HASTABLE.
	 * ( Number of rows retrieved from database).
	 *
	 * @return the row count
	 */ 
	public int getRowCount() 
	{ 
		return rowCount; 
	} 
	
	/**
	 *  
	 * Return the set - a List of hash maps , each hash map is a row.
	 *
	 * @return the row set
	 */ 
	public ArrayList<HashMap<String,String>> getRowSet() 
	{ 
		return rowSet; 
	} 
	
	/**
	 *  
	 * This method gets the records from the regular RS and puts them to the new serialized RS .
	 *
	 * @param rs ResultSet
	 * @throws SQLException the SQL exception
	 */ 
	private void populateRecords(ResultSet rs) throws SQLException 
	{ 
		int columns = 0; //number of columns
		ResultSetMetaData rsmdResult = null; //the META DATA 
		String strColname = null; //column name
		String strColvalue = null; //column value
		
		HashMap <String,String> oneRow; 
		
		//get the meta data from the result set
		rsmdResult = rs.getMetaData(); 
		//get the number of columns
		columns = rsmdResult.getColumnCount(); 
		
		try
		{
			//for every tuple - get all the fields and save them in a HashMap
			//					the key is the column name in capital letters.
			while(rs.next())
			{ 
				rowCount++;
				oneRow = new HashMap<String,String>(); 
				
				for(int i = 1; i <= columns;i++) 
				{ 
					strColname = rsmdResult.getColumnName(i); 
					strColvalue = rs.getString(strColname); 
					
					if(rs.wasNull()) 
						strColvalue=BLANKSPACE; 
					System.out.println(strColvalue);
					oneRow.put(strColname.toUpperCase(),strColvalue); 
					
					//NOTE: THE COLUMN NAMES WILL ALWAYS BE STORED IN UPPERCASE, 
					//HENCE NEED TO BE RETRIEVED IN UPPER CASE 
				} 
				rowSet.add(oneRow); 
			} 
		}
		catch(Exception e)
		{
			e.printStackTrace();	
		}
	} 
	 
}// end of class 

